function checkUpdate(callback) {  

    if((api.appVersion+'').indexOf('00.00') != -1){
        if(typeof(callback) != 'undefined'){
            callback(); 
        }
        return;
    } 

	showProgress({title:"正在检测版本"});

    var buildversion = (typeof($api.getStorage("build")) == 'undefined'?0:$api.getStorage("build")/1);
    // buildversion = 1;
    if(buildversion == 0){
        apiupdate(function(){
            smartUp(function(){
                callback(); 
                hideProgress();
            })
        }) 
    }else{
        var vm = new versionmManager(); 
        vm.update(callback);
        hideProgress();
    }  
} 


function apiupdate(callback){
    hideProgress();
    showProgress({title:"正在检测版本信息", image:"image/X5fly.gif"});
      var mam = api.require('mam'); 
    mam.checkUpdate(function(ret, err) { 
        if (ret) {               
            var result = ret.result;
            var targetVersion = result.version;
            var can = true;
            
            if(ktluser.AppMaxVersion != '' && ktluser.AppMaxVersion != targetVersion){
                can = false;
            }
            console.log(JSON.stringify(result));
 
            if(!can){
                hideProgress();
                if(typeof callback=='function'){
                    callback();
                }
                return;
            }
            if (result.update == true && result.closed == false) {
                hideProgress();
                var _html = '请升级到最新版本</br>'+api.appVersion+" ---> " + result.version;
                
                var _html = '<p>请升级到最新版本 '+api.appVersion+' ---> '+result.version+'</p>';
                _html += '<div style="font-size:16px;margin-top:10px;">'
                var ups = result.updateTip.split(' ');
                for(var i=0;i<ups.length;i++){
                    _html += '<p>'+ (i+1) +'.'+ups[i]+'</p>';
                } 
                _html += '</div>'; 
                //var str = '新版本型号:' + result.version + ';更新提示语:' + result.updateTip + ';下载地址:' + result.source + ';发布时间:' + result.time;
                ktlConfirm({
                    title : '发现新版本',
                    html : _html,
                    buttons : ['升级']
                }, function(ret, err) {
                    if (ret.value == 0) {
                        api.setKeepScreenOn({
                            keepOn: true
                        });
                        if (api.systemType == "android") {
                            var numId = "processnum" + Math.random().toString().replace('.','');
                            showProgress({title:"正在下载<span id=\""+numId+"\">0</span>%",image:"image/X5fly.gif"});
                            api.download({
                                url : result.source,
                                report : true
                            }, function(ret, err) {
                                if (ret && 0 == ret.state) {/* 下载进度 */
                                    $('#'+numId).html(ret.percent);
                                }
                                if (ret && 1 == ret.state) {/* 下载完成 */
                                    $('#'+numId)
                                       .prop('number', $('#'+numId).html()/1)
                                       .animateNumber(
                                       {
                                         number: 100
                                       },
                                       (100-$('#'+numId).html()/1)*30,
                                       function(){
                                            hideProgress();
                                            $api.setStorage("build",0); 
                                            var savePath = ret.savePath; 
                                            api.installApp({
                                                appUri : savePath
                                            });
                                       }
                                    );
                                }
                            });
                        }
                   
                    }
                });
            } else {
                hideProgress();
                if(typeof(callback) == 'function'){
                    callback();
                }
            }
        } else {
            hideProgress();
            api.toast({
                msg : "请检查网络"
            });
        }
    });
}

function smartUp(callback){ 
	var mam = api.require('mam');
	mam.checkSmartUpdate(function(ret, err){ 
	    if (ret) { 
            console.log(JSON.stringify(ret));
	    	if(typeof(ret.packages) != 'undefined'){ 
	    		var content = '';
	    		var packs = ret.packages.length; 
                var buildNo = 0;
	    		for(var i=0;i<ret.packages.length;i++){
	    			if(i==ret.packages.length-1){
                        buildNo = ret.packages[i]["incNo"];  
	    			}
	    			content += ret.packages[i]["extra"];
	    		}
	    		if(packs == 0){
	    			callback();
	    			return;
	    		}
	    		ktlConfirm({
                    title : '发现新补丁',
                    html : "升级到:" + api.appVersion + "." + ($api.getStorage("build")?$api.getStorage("build"):1),
                    buttons : ['升级']
                	}, function(ret, err) {
                		mam.startSmartUpdate(function(ret, err){ 
					    if (ret) {  
                            showProgress({title:ret.current+'/'+ret.total +'个 ' + ret.progress + '%'});
                            if(ret.current == ret.total){
                                $api.setStorage("build",buildNo);  
                                api.rebootApp();  
                            }  
					    } else {
					    	alert(JSON.stringify(err));
					    }
					});
                }); 
			}else{
				callback();
			}
	    } else { 
	    	alert(JSON.stringify(err));
	    }
	});  
}

function versionmManager(){  
    this.version = '';    

    var zipList = [];
    var zip_path = "/Resources/batch";
    var error = false;

    this.update = function(callback){
        //alert(api.appVersion);
        if(error){
            return;
        }

    //    if((api.appVersion+'').indexOf('00.') != -1){
    //        if(typeof(callback) != 'undefined'){
    //            callback(); 
    //        }
    //        return;
    //    } 
        ktlapi({
            url: '/APP/Version',
            data: { 
              "VersionNo":api.appVersion,
              "PatchNo":(typeof($api.getStorage("build")) == 'undefined'?0:$api.getStorage("build")) 
            }
          }).then(data=>{  
              showProgress({title:"正在获取版本", image:"image/X5fly.gif"}); 
              if(data.data.UpdateType != null){ 
                  if(data.data.UpdateType == "Version"){
                      //apk
                    var fs = api.require('fs');
                    fs.remove({
                        path: api.fsDir + '/apks'
                    }, function(ret, err) {
                        var _html = "升级到:" + data.data.VersionNo;
                        _html += '<div style="font-size:16px;margin-top:10px;">'  
                        _html += '<p>'+data.data.Description.replace(/\[line\]/g,'<br/>')+'</p>'; 
                        _html += '</div>';   
                        ktlConfirm({
                            title : '发现新版本',
                            html : _html,
                            buttons : ['升级']
                        }, function(ret, err) { 
                            if (ret.value == 0) {
                                var apkPath = api.fsDir + '/apks/' + data.data.VersionNo + '.apk';
                                //console.log(data.data.url);
                                api.download({
                                    url: data.data.Url,
                                    savePath: apkPath,
                                    report: true,
                                    cache: true,
                                    allowResume: true
                                }, function (ret, err) {  
                                    if (ret && 0 == ret.state) {/* 下载进度 */
                                        showProgress({title:'正在下载 '+ ret.progress +'%'});
                                    }
                                    if (ret &&  1 == ret.state) {
                                        showProgress({title:'正在安装'});
                                        $api.setStorage("build",0); 
                                        api.installApp({
                                            appUri : apkPath
                                        });
                                        hideProgress();
                                    }
                                });
                            }
                        });
                        
                    });  
                  }else{
                      //build
                      var buildList = [];
                      for(var i=0;i<data.data.Patchs.length;i++){
                          var row = data.data.Patchs[i];
                          console.log(JSON.stringify(row));
                          buildList.push({
                              "version":row["VersionNo"],
                              "desc":row["Description"],
                              "url":row["Url"]});
                      }  
                    var _html = "升级到:" + api.appVersion + "." + buildList[buildList.length-1]["version"];
                    _html += '<div style="font-size:16px;margin-top:10px;">' 
                    for(var i=0;i<buildList.length;i++){
                        if(buildList[i]["desc"]==""){
                            continue;
                        }
                        _html += '<p>'+buildList[i]["desc"].replace(/\[line\]/g,'<br/>')+'</p>';
                    } 
                    _html += '</div>';  
                    
                    ktlConfirm({
                        title : '发现新版本',
                        html : _html,
                        buttons : ['升级']
                    }, function(ret, err) {
                        if (ret.value == 0) {
                            console.log(1);
                            apiBuildUpdate(buildList,0,function(){   
                            //return;
                                unzip(zipList,0,function(){
                                    console.log(error);
                                    copy(function(){
                                        console.log(error);
                                        resetBuildVersionNo();
                                    });
                                }); 
                            }); 
                        }
                    }); 
                  }
              }else{
                  hideProgress(); 
                  if(typeof(callback) != 'undefined'){
                    callback();
                  }
              }
        })    
    }  

    function unzip(list,index,callback){
        //console.log(JSON.stringify(list));
        showProgress({title:"正在解压 "+(index)+"/"+list.length});
        if(list.length <= index){
            callback();
            return;
        }
        var fs = api.require('fs');
        var zip = api.require('zip');
        var save_zip_path = list[index]["save_zip_path"]; 
        zip.unarchive({
            file: save_zip_path,
            password: ''
        }, function (ret, err) {
            if (ret.status) {
                console.log('解压完成' + save_zip_path); 
                 //删除压缩包
                console.log("删除:"+save_zip_path);
                fs.remove({
                    path: save_zip_path
                }, function(ret, err) {
                    if (ret.status) {
                        unzip(list,index+1,callback); 
                    } else {
                        console.log('------------------------------');
                        error = true;
                        alert(JSON.stringify(err));
                    }
                });   
            }else{
                console.log('------------------------------');
                error = true;
                alert(JSON.stringify(err));
            }
        })
    }

    function resetBuildVersionNo(){  
        if(error){
            hideProgress();
            api.toast({
                msg:'升级失败,请联系客服'
            })
            return;
        }
        var maxBuild = zipList[zipList.length-1]["build"]; 
        console.log(error);
        if(!error){
            localStorage["opensanbox"] = true;
            $api.setStorage("build",maxBuild); 
        }
    }

    function copy(callback){
        showProgress({title:"正在复制文件"});
        var fs = api.require('fs');
        // alert(api.fsDir);
        // alert(api.wgtRootDir.replace("/"+api.appId,''));
        // alert(api.fsDir + zip_path + '/widget' + api.appId);
        // alert(api.fsDir + "/wgt/" + api.appId);
        // alert(api.wgtRootDir);
        //alert(JSON.stringify(ret));


        // alert("oldPath: "+api.fsDir + zip_path + '/widget');
        // alert("newPath: "+api.wgtRootDir); 
        // var appPath = "file:///data/user/0/com.mgslove.cfe/weiget";
        // alert(api.boxDir);
        var fromPath = api.fsDir + zip_path + '/widget';
        fs.copyTo({
            oldPath: fromPath,
            newPath: api.wgtRootDir.replace("widget",'')
        }, function(ret, err) {
            if (ret.status) {
                //console.log(JSON.stringify(ret));
                //删除下载文件
                fs.remove({
                    path: fromPath
                }, function(ret, err) {
                    if (ret.status) {
                        //console.log(JSON.stringify(ret)); 
                        //重置版本号
                        callback();
                        api.rebootApp(); 
                    } else {
                        alert(JSON.stringify(err)); 
                        console.log('------------------------------');
                        error = true;
                    }
                });
            } else {
                alert(JSON.stringify(err)); 
                console.log('------------------------------');
                error = true;
            }
        });
    }

    
    function apiBuildUpdate(buildList,index,callback){
        if(error){
            return;
        }
        //showProgress({title:"正在下载 "+(index)+"/"+buildList.length});
        if(buildList.length <= index){
            callback();
            return;
        } 
        var zip_path_z = buildList[index]["url"];   
        var zipName = zip_path_z.split('/')[zip_path_z.split('/').length-1]; 
        var save_zip_path = api.fsDir + zip_path + '/' + zipName; 
        api.download({
            url: zip_path_z,
            savePath: save_zip_path,
            report: true,
            cache: true,
            allowResume: true
        }, function (ret, err) {  
            // console.log(JSON.stringify(err));
            // console.log(JSON.stringify(ret));
            // if(err==""){  
            //     hideProgress();
            //     api.toast({
            //         msg:'升级失败,请联系客服'
            //     })
            //     error = true;
            //     return;
            // }
            if (ret && 0 == ret.state) {/* 下载进度 */ 
                showProgress({title:(index+1)+'/'+buildList.length +'个 ' + ret.progress + '%'});
            }
            if (ret &&  1 == ret.state) {
                zipList.push({"save_zip_path":save_zip_path,"build":buildList[index]["version"]}); 
                apiBuildUpdate(buildList,index+1,callback);
            }
        });   
    }
}